﻿#include "injectorwindow.h"
#include "injectoradddialog.h"
#include "../model/injectortablemodeldelegate.h"
#include "../../include/macro.h"

InjectorWindow::InjectorWindow()
{
    setup_ui();
    setup_model();
    setup_ui_slots();

    //sql
    sqlThread = new SqlThread("injector", "injectorManage");
    //add
    connect(this, &InjectorWindow::sig_add, sqlThread, &SqlThread::slt_addInjector);
    connect(sqlThread, &SqlThread::sig_lastId, this, &InjectorWindow::slt_addgetId);
    //delete
    connect(this, &InjectorWindow::sig_delete, sqlThread, &SqlThread::slt_deleteInjector);
    //update
    connect(injectorSettingWidget->okButton,&QPushButton::clicked, this, &InjectorWindow::confirmSetting);
    connect(this, &InjectorWindow::sig_updateSetting, sqlThread, &SqlThread::slt_updateInjectorSetting);
    connect(this, &InjectorWindow::sig_updateInfo, sqlThread, &SqlThread::slt_updateInjectorInfo);
    connect(this, &InjectorWindow::sig_updateStatus, sqlThread, &SqlThread::slt_updateInjectorStatus);

    //serial
    serialThread = new SerialThread();
    connect(serialThread, &SerialThread::sig_serialData, this, &InjectorWindow::slt_serialData);
    connect(this, &InjectorWindow::sig_respond, serialThread, &SerialThread::slt_writeData);

    serialThread->start();
    sqlThread->start();
}

InjectorWindow::~InjectorWindow()
{

}

void InjectorWindow::slt_serialData(const SerialPack& pack)
{
    const InjectorData& data = m_modelInjectorTable->ip2data(pack.ip);

    emit sig_updateStatus(pack, data.id);
    if(pack.status != 0)
        injectorSettingWidget->showWarning(QDateTime::currentDateTime().toString("yyyy-mm-dd hh:MM:ss ")
                                           + "injector " + data.name + " is offline..");
    QByteArray retdata(32,0);
    retdata[0] = 0x00;
    retdata[1] = 0x02;
    retdata[2] = 0x00;

    /*
    retdata[3]
    retdata[4]
    //ip
    retdata[5] =
    retdata[6] =
    retdata[7] =

    */
    //isfirst
    retdata[8] = 0x01;

    //get data.settings
    //inj_vol
    retdata[9] = data.settings.inject_volume >> 8;
    retdata[10] = data.settings.inject_volume & 0x000000ff;
    //inj_p
    retdata[11] = data.settings.inject_period >> 8;
    retdata[12] = data.settings.inject_period & 0x000000ff;
    //max_c
    retdata[13] = 0x00;
    retdata[14] = 0x00;
    //min_v
    retdata[15] = 0x00;
    retdata[16] = 0x00;
    //comm_p
    retdata[17] = data.settings.comm_period >> 8;
    retdata[18] = data.settings.comm_period & 0x000000ff;

    retdata[19] = 0x00;

    //CRC
    retdata[30] = 0xcc;
    retdata[31] = 0xcc;

    m_modelInjectorTable->updateStatus(pack);
    emit sig_respond(retdata);
};

void InjectorWindow::confirmSetting()
{
    QModelIndex index = injTableView->currentIndex();
    if(index.isValid() && injectorSettingWidget->checkSetting())
    {
        InjectorData data = m_modelInjectorTable->getDeviceData(index);
        QString name = injectorSettingWidget->name_ed->text();
        QString position = injectorSettingWidget->pos_ed->text();
        if(data.name != name || data.position != position)
        {
            data.name = name;
            data.position = position;
            emit sig_updateInfo(name, position, data.id);
        }
        InjectorSetting settings = injectorSettingWidget->getSetting();
        qDebug()<< data.settings.inject_volume <<" "<< settings.inject_volume<<endl;
        if(data.settings != settings)
        {
            data.settings = settings;
            //emit sig_updateSetting(settings, data.id);
        }
        m_modelInjectorTable->setDeviceData(index, data);
        injectorSettingWidget->setInfo(data);
    }
    else
    {
        QMessageBox::warning(NULL, QStringLiteral("设置失败"), QStringLiteral("未选择设备"));
    }
}

void InjectorWindow::setup_ui_slots()
{
    //table
    connect(injTableView, &QTableView::clicked, this, &InjectorWindow::slt_selected);
    connect(addButton, &QAbstractButton::clicked, this, &InjectorWindow::slt_addDialog);
    connect(injTableView, &QTableView::customContextMenuRequested, this, &InjectorWindow::slt_showMenu);
    connect(deleteAction, &QAction::triggered, this, &InjectorWindow::slt_delete);
}

void InjectorWindow::slt_delete()
{
    auto index = injTableView->currentIndex();
    emit sig_delete(m_modelInjectorTable->getDeviceId(index));
    m_modelInjectorTable->deleteDevice(index);
}

void InjectorWindow::slt_showMenu(const QPoint& point)
{
    auto index = injTableView->indexAt(point);
    if (index.isValid())
    {
        menu->exec(QCursor::pos());
    }
}

void InjectorWindow::slt_addgetId(uint id)
{
    m_modelInjectorTable->lastDevice().id = id;
}

void InjectorWindow::slt_addDialog()
{
    // add dialog
    InjectorAddDialog dialog;
    if(dialog.exec())
    {
        InjectorData data = dialog.getInjData();
        emit sig_add(data);
        m_modelInjectorTable->addDevice(data);
    }
}

void InjectorWindow::slt_selected(const QModelIndex &index)
{
    const InjectorData& data = m_modelInjectorTable->getDeviceData(index);
    injectorSettingWidget->setInfo(data);
}

void InjectorWindow::setup_model()
{
    m_modelInjectorTable = new InjectorTableModel();
    QList<InjectorData> datalist;
    {
        QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL", "inj temp");
        db.setHostName("localhost");
        db.setPort(3306);
        db.setDatabaseName("dtu");
        db.setUserName(TO_STR(DB_USERNAME));
        db.setPassword("");
        db.open();
        if(!db.open())
        {
            qDebug()<<"mysql: initial connect injector error"<<db.lastError().text();
            return;
        }
        else
             qDebug()<<"mysql: initial connect injector  OK";

        QString str("SELECT * FROM injector.info");
        QSqlQuery query(str,db);
        query.exec();
        while(query.next())
        {
            InjectorData data;
            data.id = query.value(0).toInt();
            data.ip = query.value(1).toInt();
            data.name = query.value(2).toString();
            data.position = query.value(3).toString();
            data.status = query.value(4).toInt();
            data.battery = query.value(5).toInt();
            data.oil = query.value(6).toInt();
            data.settings.inject_period = query.value(7).toInt();
            data.settings.comm_period = query.value(8).toInt();
            data.settings.inject_volume = query.value(9).toInt();
            data.settings.max_current = query.value(10).toInt();
            data.settings.min_volt = query.value(11).toInt();
            datalist.append(data);
        }
        db.close();
    }
    QSqlDatabase::removeDatabase("inj temp");
    m_modelInjectorTable->setList(datalist);

    QStringList header;
    header<<QStringLiteral("工作状态")<<QStringLiteral("润滑机")<<QStringLiteral("剩余电量")<<QStringLiteral("剩余油脂量");
    m_modelInjectorTable->setHorizontalHeader(header);
    injTableView->setModel(m_modelInjectorTable);
    setup_tableview();

    InjectorTableModelDelegate* idelegate = new InjectorTableModelDelegate();
    injTableView->setItemDelegate(idelegate);
    emit m_modelInjectorTable->layoutChanged();
}

void InjectorWindow::setup_ui()
{
    QVBoxLayout* layout = new QVBoxLayout();
    QLayout* datalay = setup_injTable();
    layout->addLayout(datalay);
    injectorSettingWidget = new InjectorSettingWidget();
    layout->addWidget(injectorSettingWidget);
    layout->setStretchFactor(datalay, 3);
    layout->setStretchFactor(injectorSettingWidget, 2);

    layout->setMargin(0);
    layout->setSpacing(2);
    setLayout(layout);
}

QLayout* InjectorWindow::setup_injTable()
{
    QGridLayout* layout = new QGridLayout();
    QLabel* injdataTitle = new QLabel(QStringLiteral("润滑机数据"));
    injdataTitle->setStyleSheet("background-color:#d4d0c8;");
    injdataTitle->setAlignment(Qt::AlignCenter);

    addButton = new QToolButton();
    addButton->setIcon(QIcon(":/pics/rc/add.jpg"));

    //injector data table
    injTableView = new QTableView();
    injTableView->setContextMenuPolicy(Qt::CustomContextMenu);
    menu = new QMenu(injTableView);
    deleteAction = new QAction(QStringLiteral("删除设备"));
    menu->addAction(deleteAction);

    layout->addWidget(injdataTitle,0,0,1,3);
    layout->addWidget(addButton,0,3,1,1);
    layout->addWidget(injTableView,1,0,19,4);

    return layout;
}

void InjectorWindow::setup_tableview()
{
    injTableView->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
    injTableView->horizontalHeader()->setSectionResizeMode(0, QHeaderView::Fixed);
    injTableView->horizontalHeader()->setSectionResizeMode(1, QHeaderView::Fixed);
    injTableView->setColumnWidth(0,65);
    injTableView->setSelectionBehavior(QAbstractItemView::SelectRows);
    injTableView->setSelectionMode(QAbstractItemView::SingleSelection);
}


